package com.yixin.token.utils;

import com.yixin.token.exceptions.ServerException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

public class HttpClientUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpClientUtils.class);
    private static final String CONTENT_TYPE_JSON = "application/json;charset=UTF-8";
    private static final String CHARSET_UTF_8 = "UTF-8";

    public static String post(String url, String jsonStr) throws ServerException {
        String res = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity;
        try {
            stringEntity = new StringEntity(jsonStr);
        } catch (UnsupportedEncodingException e) {
            logger.error("http post json set entity error!", e);
            return null;
        }
        httpPost.setHeader("Content-Type", CONTENT_TYPE_JSON);
        httpPost.setEntity(stringEntity);


        CloseableHttpResponse response = null;
        try {
            logger.info("请求url:{}", httpPost.getURI());
            response = httpclient.execute(httpPost);
            logger.info("返回code:{}", response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                res = EntityUtils.toString(entity, CHARSET_UTF_8);
                logger.error("非200响应，http状态码:{}, 响应体:{}", response.getStatusLine().getStatusCode(), res);
                throw new ServerException(String.valueOf(response.getStatusLine().getStatusCode()), response.getStatusLine().getReasonPhrase());
            }
            HttpEntity entity = response.getEntity();
            res = EntityUtils.toString(entity, CHARSET_UTF_8);
            logger.info("返回值:{}", res);
        } catch (IOException e) {
            logger.error("请求异常!", e);
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    logger.error("close httpClient exception!", e);
                }
            }
        }
        return res;
    }

    public static String downloadFile(String url, String jsonStr) throws ServerException {
        String res = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        StringEntity stringEntity;
        try {
            stringEntity = new StringEntity(jsonStr);
        } catch (UnsupportedEncodingException e) {
            logger.error("http post json set entity error!", e);
            return null;
        }
        httpPost.setHeader("Content-Type", CONTENT_TYPE_JSON);
        httpPost.setEntity(stringEntity);


        CloseableHttpResponse response = null;
        try {
            logger.info("请求url:{}", httpPost.getURI());
            response = httpclient.execute(httpPost);
            logger.info("返回code:{}", response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                res = EntityUtils.toString(entity, CHARSET_UTF_8);
                logger.error("非200响应，http状态码:{}, 响应体:{}", response.getStatusLine().getStatusCode(), res);
                throw new ServerException(String.valueOf(response.getStatusLine().getStatusCode()), response.getStatusLine().getReasonPhrase());
            }
            String signature = "";
            Header contentHead = response.getFirstHeader("signature");
            signature = contentHead != null ? contentHead.getValue() : "";
            logger.info("文件签名:{}", signature);
            if (StringUtils.isBlank(signature)) {
                throw new ServerException(String.valueOf(response.getStatusLine().getStatusCode()), "签名为空！");
            }
            HttpEntity entity = response.getEntity();
            res = EntityUtils.toString(entity, CHARSET_UTF_8);
            if (!signature.equals(SMTool.sm3Digest(res))) {
                throw new ServerException(String.valueOf(response.getStatusLine().getStatusCode()), "签名验证失败！");
            }

            logger.info("返回值:{}", res);
        } catch (IOException e) {
            logger.error("请求异常!", e);
        } finally {
            if (httpclient != null) {
                try {
                    httpclient.close();
                } catch (IOException e) {
                    logger.error("close httpClient exception!", e);
                }
            }
        }
        return res;
    }
}
